import pandas as pd
from pymysql.converters import escape_string

import pymysql
import asyncio
import jieba

# 打开数据库连接
from aiohttp import ClientSession

db_config = {
    'host': '3a524389i9.qicp.vip', # 主机
    'user': 'root',       #用户名
    'password': 'zjdx20210126',  #密码
    'port': 63307,         #端口 3306
    'database':'uni_center'   #数据库名
}
key_points_df = pd.DataFrame(columns=['datetime', 'value', 'event'])

#range_end = pd.DataFrame([{
#    'datetime': p.datetime,
#    'value': p.value,
#    'event': f'{action}结束',
#}])
#self.key_points_df = pd.concat([self.key_points_df, range_start], ignore_index=True)

async def main():
    jieba.load_userdict("C:\\Users\\Administrator\\Desktop\\联创接口\\zjdx.txt")

    # seg_list = jieba.cut("我来到北京清华大学", cut_all=True)
    # print("Full Mode: " + "/ ".join(seg_list))  # 全模式
    db = pymysql.connect(**db_config)
    # 使用cursor()方法获取操作游标a
    cursor = db.cursor()
    # SQL 查询语句
    sql = "select max(id),uni_id,max(book_name),max(org_id) from c_book202305241100 GROUP BY uni_id "
    try:
        # 执行SQL语句
        cursor.execute(sql)
        # 获取所有记录列表
        results = cursor.fetchall()
        for row in results:
            book_id = row[0]
            uni_id = row[1]
            book_name = row[2]
            org_id = row[3]
            seg_list = jieba.cut(book_name, cut_all=False)
            # print("Full Mode: " + "/ ".join(seg_list))  # 全模式
            for seg in seg_list:
                if len(seg) >= 2:
                    print(seg)
                    sql = 'INSERT INTO word_c_book_20230525(book_id, word, org_id, uni_id, book_name) VALUES ({},"{}","{}","{}","{}");'.format(book_id, seg, org_id, uni_id, escape_string(book_name))
                    print(sql)
                    cursor.execute(sql)
                    db.commit()




    except:
        print("Error: unable to fetch data")

    # 关闭数据库连接
    db.close()

if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())
